package com.ynet.hmds28.user.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.boot.hsf.annotation.HSFProvider;
import com.alibaba.druid.util.StringUtils;
import com.ynet.hm.user.service.SubscribeService;
import com.ynet.hm.utils.UuidUtil;
import com.ynet.hm.utils.config.Result;
import com.ynet.hm.utils.config.ResultUtil;
import com.ynet.hm.utils.enums.ExceptionEnum;
import com.ynet.hm.utils.exception.MyException;
import com.ynet.hmds28.user.dao.ServiceconsumeDao;
import com.ynet.hmds28.user.dao.ServiceprovideDao;
import com.ynet.hmds28.user.model.Serviceconsume;
import com.ynet.hmds28.user.model.ServiceconsumeQuery;
import com.ynet.hmds28.user.model.Serviceprovide;
@Transactional
@HSFProvider(serviceInterface = SubscribeService.class, serviceVersion = "1.0.0",serviceGroup = "hmds28")
public class SubscribeServiceImpl implements SubscribeService {
	@Autowired
	private ServiceprovideDao serviceprovideDao;
	@Resource
	private ServiceconsumeDao serviceconsumeDao;
	@Override
	public Result<?> SubscribeService(String userId, String serviceId) {
		//开启GTS事务
		serviceconsumeDao.enableTXC();
		if(StringUtils.isEmpty(userId)){
			throw new MyException(ExceptionEnum.GETUSER_ERROR);
		}
		//查询服务是否存在
		Serviceprovide sp=serviceprovideDao.selectByPrimaryKey(serviceId);
		if(sp==null){
			throw new MyException(ExceptionEnum.SERVICE_NOT_HAVE);
		}
		ServiceconsumeQuery scq=new ServiceconsumeQuery();
		scq.createCriteria().andUseridEqualTo(userId).andSeviceproviceidEqualTo(serviceId);
		List<Serviceconsume> scs=serviceconsumeDao.selectByExample(scq);
		if(!CollectionUtils.isEmpty(scs)){
			throw new MyException(ExceptionEnum.SERVICE_IS_SUB);
		}
		Serviceconsume ss=new Serviceconsume();
		ss.setCallcost("0");
		ss.setCallnum("0");
		ss.setCreatetime(new Date());
		ss.setServiceconsumeid(UuidUtil.getUUid());
		ss.setSeviceproviceid(serviceId);
		ss.setUserid(userId);
		serviceconsumeDao.insertSelective(ss);
		return ResultUtil.success();
	}

}
